#include "hbdatahandler.h"

namespace Diablo3{
    QString DOCTYPEString(DOCTYPES type){
        switch(type){
        case CHARACTER: return QString("Character");
        case ABILITIES: return QString("Abilities");
        default: return QString("Invalid DOCTYPE");
        }
    }
}

HBDataHandler::HBDataHandler(QString fp,Diablo3::DOCTYPES docType,QString name)
{
    filePath=fp;
    doc = QDomDocument(Diablo3::DOCTYPEString(docType));
    QDomElement root = doc.createElement(name);
    doc.appendChild(root);

    QDomElement tag = doc.createElement("Greetings");
    root.appendChild(tag);

    QDomText t = doc.createTextNode("Hello World");
    tag.appendChild(t);
}

QDomDocument & HBDataHandler::getDoc()
{
    return doc;
}

void HBDataHandler::setFilePath(QString path)
{
    filePath=path;
}

void HBDataHandler::save()
{
    if(filePath!=NULL){
        //dosomething
        if(!QDir("data").exists())
            throw CException("Subdirectory \"data\" is missing!");
        QFile file(filePath);
        if(!file.open(QIODevice::WriteOnly|QIODevice::Text))
            throw CException((QString("Unable to open file ")+filePath+QString(" !")).toStdString().c_str());
        file.write(doc.toByteArray());
        file.close();
    }
}

void HBDataHandler::load()
{
    if(filePath!=NULL){
        QFile file(filePath);
        if(!file.exists())
            throw CException(filePath," does not exists!");
        QXmlSimpleReader xmlReader;
        QXmlInputSource *source = new QXmlInputSource(&file);
        QXmlDefaultHandler  *chandler = new QXmlDefaultHandler();
        QXmlDefaultHandler  *ehandler = new QXmlDefaultHandler();
        xmlReader.setContentHandler(chandler);
        xmlReader.setErrorHandler(ehandler);
        bool ok = xmlReader.parse(source);
        if(!ok)
            throw CException("Parsing error! File: ",filePath);
    }
}
